package com.dd.cloud.common.utils;

import com.dd.cloud.common.constants.ZekeConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 图形验证码生成工具类
 *
 * @author zk
 */
@Slf4j
public class RandomImageCodeUtil {
    /**
     * session 键值
     */
    public static final String RANDOM_CODE_KEY = "RANDOMIMGCODEKEY";
    /**
     * 随机产生数字与字母组合的字符串
     */
    private static final String RAND_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    /**
     * 万能验证码
     */
    private static final String SUCCESS = "1946";
    // 图片宽
    private final int width = 68;
    // 图片高
    private final int height = 27;
    // 干扰线数量
    private final int lineSize = 15;
    // 随机产生字符数量
    private final int stringNum = 4;

    private final Random random = new Random();

    /**
     * 获得字体
     */
    private Font getFont() {
        return new Font("Fixedsys", Font.BOLD, 15);
    }

    /**
     * 获得颜色
     */
    private Color getRandColor(int fc, int bc) {
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc - 16);
        int g = fc + random.nextInt(bc - fc - 14);
        int b = fc + random.nextInt(bc - fc - 18);
        return new Color(r, g, b);
    }

    /**
     * 生成随机图片
     */
    public void getRandCode(HttpServletRequest request, HttpServletResponse response) {
        String randomString = getRandCode(response);
        HttpSession session = request.getSession();
        //将生成的随机字符串保存到session中
        session.removeAttribute(RANDOM_CODE_KEY);
        session.setAttribute(RANDOM_CODE_KEY, randomString);
    }

    /**
     * 生成随机图片
     */
    public void getRandCode(StringRedisTemplate redisTemplate, String key, HttpServletResponse response) {
        String randomString = getRandCode(response);
        // 将随机字符串保存redis中 本设置有效期
        redisTemplate.opsForValue().set(key, randomString, ZekeConstants.CommonConstants.IMAGE_RANDOM_CODE_TIME, TimeUnit.MINUTES);
    }

    /**
     * 生成随机图片
     */
    public String getRandCode(HttpServletResponse response) {
        // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        // 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
        Graphics graphics = image.getGraphics();
        //图片大小
        graphics.fillRect(0, 0, width, height);
        //字体大小
        graphics.setFont(new Font("Times New Roman", Font.PLAIN, 15));
        //字体颜色
        graphics.setColor(getRandColor(110, 133));
        // 绘制干扰线
        for (int i = 0; i <= lineSize; i++) {
            drawLine(graphics);
        }
        // 绘制随机字符
        String randomString = "";
        for (int i = 1; i <= stringNum; i++) {
            randomString = drawString(graphics, randomString, i);
        }
        log.info(randomString);
        graphics.dispose();
        try {
            //将内存中的图片通过流动形式输出到客户端
            ImageIO.write(image, "JPEG", response.getOutputStream());
        } catch (Exception e) {
            log.error("将内存中的图片通过流动形式输出到客户端失败>>>>   ", e);
        }
        return randomString;
    }

    /**
     * 验证图片验证码
     *
     * @return
     */
    public static boolean checkImgRandom(String inputStr, HttpSession session) {
        if (StringUtils.isBlank(inputStr)) {
            return false;
        }
        inputStr = inputStr.toUpperCase();
        String random = (String) session.getAttribute(RANDOM_CODE_KEY);
        log.info("生成的验证码:{},输入的验证码:{}", random, inputStr);
        if (inputStr.equals(random)) {
            return true;
        }
        return inputStr.equals(SUCCESS);
    }

    /**
     * 绘制干扰线
     */
    private void drawLine(Graphics g) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(13);
        int yl = random.nextInt(15);
        g.drawLine(x, y, x + xl, y + yl);
    }

    /**
     * 获取随机的字符
     */
    public String getRandomString(int num) {
        return String.valueOf(RAND_STRING.charAt(num));
    }

    /**
     * 验证图片验证码
     *
     * @return
     */
    public static boolean checkImgRandom(String inputStr, StringRedisTemplate redisTemplate, String key) {
        if (StringUtils.isBlank(inputStr)) {
            return false;
        }
        inputStr = inputStr.toUpperCase();
        String random = redisTemplate.opsForValue().get(key);
        log.info("生成的验证码:{},输入的验证码:{}", random, inputStr);
        if (inputStr.equals(random)) {
            redisTemplate.delete(key);
            return true;
        }
        return inputStr.equals(SUCCESS);
    }

    /**
     * 绘制字符串
     */
    private String drawString(Graphics g, String randomString, int i) {
        g.setFont(getFont());
        g.setColor(new Color(random.nextInt(101), random.nextInt(111), random.nextInt(121)));
        String rand = String.valueOf(getRandomString(random.nextInt(RAND_STRING.length())));
        randomString += rand;
        g.translate(random.nextInt(3), random.nextInt(3));
        g.drawString(rand, 11 * i, 16);
        return randomString;
    }

    /**
     * 删除图片验证码
     *
     * @return
     */
    public static boolean delImgRandom(HttpSession session) {
        session.removeAttribute(RANDOM_CODE_KEY);
        return true;
    }
}
